package com.jrx.anytxn.transaction.service.impl;

import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.customer.entity.CmCustomerFirstLevel;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.entity.PrBlockCode;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtPrBlockCodeMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.transaction.bean.BlockCodeSaveBean;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.entity.AmLoanAccountInfo;
import com.jrx.anytxn.transaction.entity.TlCustomerBlockCode;
import com.jrx.anytxn.transaction.service.ICustBlockCodeService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @program: anytxn-cf-transaction
 * @description: 客户封锁码操作类
 * @author: lbz
 **/
@Service
public class CustBlockCodeServiceImpl implements ICustBlockCodeService {

    private static final Logger logger = LoggerFactory.getLogger(CustBlockCodeServiceImpl.class);

    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private ISegmentService segmentService;
    @Resource
    private ExtPrBlockCodeMapper extPrBlockCodeMapper;

    @Override
    public BlockCodeSaveBean buildBlockCode(CmCustomerFirstLevel firstLevel,List<AmLoanAccountInfo> accountInfoList) throws TxnBizException {
        BlockCodeSaveBean blockCodeSaveBean = new BlockCodeSaveBean();

        int delqDays = 0 ;//逾期天数

        if(CollectionUtils.isNotEmpty(accountInfoList)){
            //获取客户当前最大逾期天数
            for(AmLoanAccountInfo amLoanAccountInfo : accountInfoList){
                if(TransBizConstant.ACCOUNT_STATUS_2.equals(amLoanAccountInfo.getAccountStatus())&&
                        amLoanAccountInfo.getDelqDays() > delqDays){
                    delqDays = amLoanAccountInfo.getDelqDays();
                }
            }
        }
        logger.info("客户封锁码处理,客户号:{}，逾期天数{}",firstLevel.getCustomerId(),delqDays);


        //根据逾期天数查询 封锁码规则 获取优先级最高的封锁码
        String blockCode = extPrBlockCodeMapper.findByDelqDaysAndTenId(firstLevel.getTenantId(),delqDays);
        String preBlockCode = firstLevel.getBlockCode();//原封锁码
        logger.info("客户封锁码处理,客户号:{}，原封锁码：{}，新封锁码：{}",firstLevel.getCustomerId(),preBlockCode,blockCode);

        PrOrganizationTable org = organizationTableService.findByOrId(TransBizConstant.DEFAULT_ORG_ID, firstLevel.getTenantId());
        Date today = org.getToday();

        if(StringUtils.isBlank(preBlockCode) && StringUtils.isNotBlank(blockCode)){

            firstLevel.setBlockCode(blockCode);
            firstLevel.setBlockCodeUpdateDate(today);

            //生成客户封锁码流水
            TlCustomerBlockCode tlCustomerBlockCode = buildTlBlockCode(firstLevel,preBlockCode,blockCode,today);

            blockCodeSaveBean.setSaveBlockCode(tlCustomerBlockCode);

        }else if(StringUtils.isNotBlank(preBlockCode) && StringUtils.isBlank(blockCode)){

            firstLevel.setBlockCode(" ");
            firstLevel.setBlockCodeUpdateDate(today);

            //生成客户封锁码流水
            TlCustomerBlockCode tlCustomerBlockCode = buildTlBlockCode(firstLevel,preBlockCode,firstLevel.getBlockCode(),today);

            blockCodeSaveBean.setSaveBlockCode(tlCustomerBlockCode);
        }else if((StringUtils.isBlank(preBlockCode) && StringUtils.isBlank(blockCode)) || preBlockCode.equals(blockCode)){
            return null;
        }else if(!preBlockCode.equals(blockCode)){
            //获取封锁码属性
            PrBlockCode prePrBlockCode = extPrBlockCodeMapper.selectByTenIdAndBlockCodeAndStatus(firstLevel.getTenantId(),preBlockCode,TransBizConstant.STATUS_1);
            PrBlockCode newPrBlockCode = extPrBlockCodeMapper.selectByTenIdAndBlockCodeAndStatus(firstLevel.getTenantId(),preBlockCode,TransBizConstant.STATUS_1);
            //只有新封锁码优先级>=原封锁码优先级才更新
            if(newPrBlockCode.getCodePriority() >= prePrBlockCode.getCodePriority()){
                firstLevel.setBlockCode(blockCode);
                firstLevel.setBlockCodeUpdateDate(today);

                //生成客户封锁码流水
                TlCustomerBlockCode tlCustomerBlockCode = buildTlBlockCode(firstLevel,preBlockCode,blockCode,today);
                blockCodeSaveBean.setSaveBlockCode(tlCustomerBlockCode);
            }
        }
        return blockCodeSaveBean;
    }

    /**
     * 生成封锁码流水
     * @param firstLevel
     * @param preBlockCode
     * @param blockCode
     * @param today
     * @return
     */
    private TlCustomerBlockCode buildTlBlockCode(CmCustomerFirstLevel firstLevel,String preBlockCode,String blockCode,Date today) throws TxnBizException {
        TlCustomerBlockCode tlCustomerBlockCode = new TlCustomerBlockCode();
        try {
            tlCustomerBlockCode.setId(segmentService.getId(TransBizConstant.TL_CUSTOMER_BLOCK_CODE));
        } catch (SegmentException e) {
            logger.error("主键生成错误", e);
            throw new TxnBizException(TxnRespCode.ERROR.getUserTips());
        }
        tlCustomerBlockCode.setTenantId(firstLevel.getTenantId());
        tlCustomerBlockCode.setOrganizationId(null == firstLevel.getOrganizationId()?TransBizConstant.DEFAULT_ORG_ID:firstLevel.getOrganizationId());
        tlCustomerBlockCode.setCustomerId(firstLevel.getCustomerId());
        tlCustomerBlockCode.setBlockCode(blockCode);
        tlCustomerBlockCode.setPreBlockCode(preBlockCode);
        tlCustomerBlockCode.setBusinessDate(today);
        tlCustomerBlockCode.setCreateBy(TransBizConstant.SYS_OPRATE);

        return tlCustomerBlockCode;
    }
}
